<?php

if (!defined('TOBBIVM'))
	header('location:/template/notrepassing.php');
/**
 * This file is part of TobbiVMShop.
 *
 * TobbiVMShop is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TobbiVMShop is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TobbiVMShop.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * class to manage the gallery-system
 * 
 * @version    $Id$
 * @package    TobbiVM-Shop
 * @copyright  Copyright (C) 2015
 * @author     Norbert Gebert
 * @license    GPL3
 */
class fancybox extends validate
{

	private $_config = array();
	private $_script = "<script type=\"text/javascript\">
		$(document).ready(function() {
			/*
			 *  Simple image gallery. Uses default settings
			 */

      $('.fancybox').fancybox({
            maxWidth: {maxWidth},
				maxHeight: {maxHeight},
				openEffect: '{openEffect}',
				closeEffect: '{closeEffect}',
				nextEffect: '{nextEffect}',
				prevEffect: '{prevEffect}',
				openSpeed: {openSpeed},
				closeSpeed: {closeSpeed},
				nextSpeed: {nextSpeed},
				prevSpeed: {prevSpeed},
				openOpacity: {openOpacity},
				closeOpacity: {closeOpacity},
				arrows: {arrows},
				closeBtn: {closeBtn},
				mouseWheel: {mouseWheel},
				autoPlay: {autoPlay},
            playSpeed: {playSpeed}
       });
		 });
	</script>
	<style type=\"text/css\">
		.fancybox-custom {
			box-shadow: 0 0 50px #222;
			max-width: {width}px;
		}
	</style>";

	/*
	 * Initialize from settings. They are changeable in the Backend.
	 * Included maxvalue-, minvalue, string... and typ.
	 */

	public function __construct()
	{
		$this->_config[] = array('text' => _('Width'), 'name' => 'width',
		 'typ' => 'i', 'value' => 650, 'min' => 100, 'max' => 3000, 'set' => '');
		$this->_config[] = array('text' => _('maxWidth'), 'name' => 'maxWidth',
		 'typ' => 'i', 'value' => 800, 'min' => 150, 'max' => 3000, 'set' => '');
		$this->_config[] = array('text' => _('maxHeight'), 'name' => 'maxHeight',
		 'typ' => 'i', 'value' => 600, 'min' => 100, 'max' => 3000, 'set' => '');

		$this->_config[] = array('text' => _('Open effect'), 'name' => 'openEffect',
		 'typ' => 's', 'value' => 'elastic', 'min' => 0, 'max' => 0,
		 'set' => 'elastic,fade,none');
		$this->_config[] = array('text' => _('Close effect'), 'name' => 'closeEffect',
		 'typ' => 's', 'value' => 'elastic', 'min' => 0, 'max' => 0,
		 'set' => 'elastic,fade,none');
		$this->_config[] = array('text' => _('Next effect'), 'name' => 'nextEffect',
		 'typ' => 's', 'value' => 'elastic', 'min' => 0, 'max' => 0,
		 'set' => 'elastic,fade,none');
		$this->_config[] = array('text' => _('Preview effect'), 'name' => 'prevEffect',
		 'typ' => 's', 'value' => 'elastic', 'min' => 0, 'max' => 0,
		 'set' => 'elastic,fade,none');

		$this->_config[] = array('text' => _('Open speed'), 'name' => 'openSpeed',
		 'typ' => 'i', 'value' => 500, 'min' => 0, 'max' => 10000, 'set' => '');
		$this->_config[] = array('text' => _('Close speed'), 'name' => 'closeSpeed',
		 'typ' => 'i', 'value' => 500, 'min' => 0, 'max' => 10000, 'set' => '');
		$this->_config[] = array('text' => _('Next speed'), 'name' => 'nextSpeed',
		 'typ' => 'i', 'value' => 500, 'min' => 0, 'max' => 10000, 'set' => '');
		$this->_config[] = array('text' => _('Preview speed'), 'name' => 'prevSpeed',
		 'typ' => 'i', 'value' => 500, 'min' => 0, 'max' => 10000, 'set' => '');

		$this->_config[] = array('text' => _('Open Opacity'), 'name' => 'openOpacity',
		 'typ' => 'b', 'value' => 1, 'min' => 0, 'max' => 1, 'set' => '');
		$this->_config[] = array('text' => _('Close Opacity'), 'name' => 'closeOpacity',
		 'typ' => 'b', 'value' => 1, 'min' => 0, 'max' => 1, 'set' => '');

		$this->_config[] = array('text' => _('Navigation Arrows'), 'name' => 'arrows',
		 'typ' => 'b', 'value' => 1, 'min' => 0, 'max' => 1, 'set' => '');
		$this->_config[] = array('text' => _('Close Button'), 'name' => 'closeBtn',
		 'typ' => 'b', 'value' => 1, 'min' => 0, 'max' => 1, 'set' => '');
		$this->_config[] = array('text' => _('Mouse wheel'), 'name' => 'mouseWheel',
		 'typ' => 'b', 'value' => 1, 'min' => 0, 'max' => 1, 'set' => '');
		$this->_config[] = array('text' => _('Autoplay'), 'name' => 'autoPlay',
		 'typ' => 'b', 'value' => 0, 'min' => 0, 'max' => 1, 'set' => '');
		$this->_config[] = array('text' => _('Playspeed'), 'name' => 'playSpeed',
		 'typ' => 'i', 'value' => 3000, 'min' => 0, 'max' => 20000, 'set' => '');
	}

	/*
	 * Create the code to replace plugincall. 
	 * 
	 * @param string $code Plugin-call-code 
	 * @return code/replace html/text
	 */

	public function getCode($code)
	{
		$codes = explode(':', $code);
		$path = './images/user/' . $codes[1];
		$path = str_replace('}', '', $path);
		$files = scandir($path);

		foreach ($files as $value)
		{
			if ((strpos("/" . $value . "/i", '.png') >= 1 or
				strpos("/" . $value . "/i", '.gif') >= 1 or
				strpos("/" . $value . "/i", '.jpg') >= 1) and
				strpos("/" . $value . "/i", 'tbn_') == FALSE and
				strpos("/" . $value . "/i", '.txt') == FALSE)
				$fileList[] = $value;
		}
		$code = '';

		foreach ($fileList as $value)
		{
			// Create thumbnail if not found
			if (!is_file($path . '/tbn_' . $value) and
				preg_match("/tbn_/i", $value) <> 1)
				$this->_createThumbnail($path, $value, str_replace('}', '', $codes[2]));
			$alt = '';
			if (is_file($path . '/' . $value . '.txt'))
				$alt = implode("", file($path . '/' . $value . '.txt'));
			$css = '';
			if (isset($codes[3]))
				$css = 'class="' . str_replace('}', '', $codes[3]) . '" ';

			$code .= '<a class="fancybox" href="';
			$code .= $path . '/' . $value;
			$code .= '" data-fancybox-group="gallery" title="';
			$code .= $alt . '"><img ' . $css . 'src="';
			$code .= $path . '/tbn_' . $value;
			$code .= '" alt="' . $alt . '" /></a>';
		}
		return $code;
	}

	/*
	 * Create thumbnail from given image
	 * 
	 * @param string $path			Path to imagedir
	 * @param string $name			Name of imagefile
	 * @param string $thumbSize	Size og Thumbnail
	 */

	private function _createThumbnail($path, $name, $thumbSize)
	{
		$sourceImage = $path . '/' . $name;
		$path = $path . '/';
		$art = strrchr($sourceImage, ".");
		list($width, $height) = getimagesize($sourceImage);
		$ratio = $width / $height;

		// Dimension of image
		if ($ratio > 1)
		{
			$newWidth = $thumbSize;
			$newHeight = intval($thumbSize / $ratio);
		}
		else
		{
			$newHeight = $thumbSize;
			$newWidth = intval($thumbSize * $ratio);
		}

		// create image
		if (function_exists("imagecreatetruecolor"))
		{
			$thumb = @imagecreatetruecolor($newWidth, $newHeight);
		}
		else
		{
			$thumb = imagecreate($newWidth, $newHeight);
		}
		if ($art == ".jpg")
		{
			imagejpeg($thumb, $path . "temp.jpg");
			$thumb = imagecreatefromjpeg($path . "temp.jpg");
			$source = imagecreatefromjpeg($sourceImage);
		}
		else if ($art == ".gif")
		{
			imagegif($thumb, $path . "temp.gif");
			$thumb = imagecreatefromgif($path . "temp.gif");
			$source = imagecreatefromgif($sourceImage);
		}
		else if ($art == ".png")
		{
			imagepng($thumb, $path . "temp.png");
			$thumb = imagecreatefrompng($path . "temp.png");
			$source = imagecreatefrompng($sourceImage);
		}
		@imagecopyresized($thumb, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);

		// save image
		if ($art == ".png")
			imagepng($thumb, $path . 'tbn_' . $name);
		else if ($art == ".gif")
			imagegif($thumb, $path . 'tbn_' . $name);
		else
			imagejpeg($thumb, $path . 'tbn_' . $name, 100);

		//Speicherplatz wieder freigeben
		ImageDestroy($thumb);
		ImageDestroy($source);
		if ($art == ".jpg")
		{
			unlink($path . "temp.jpg");
		}
		else if ($art == ".gif")
		{
			unlink($path . "temp.gif");
		}
		else if ($art == ".png")
		{
			unlink($path . "temp.png");
		}
	}

	/*
	 * Create the config array for output. 
	 * 
	 * @param string $id Plugin-id from database 
	 * @return array assoziative with html code for template output
	 */

	public function getConfigHtml($id)
	{
		db::getInstance()->where('plugin_id', $id);
		$result = db::getInstance()->getOne('plugin');
		$buffer = explode('|', $result['plugin_config']);
		foreach ($buffer as $bufferx)
		{
			if (preg_match("/config::/i", $bufferx) == 1)
			{
				$buffery = explode('::', $bufferx);
				$savedValues = explode(',', $buffery[1]);
				break;
			}
		}

		$helpx = $result['plugin_help'];
		unset($result);
		unset($bufferx);
		unset($buffery);

		$html = '';

		foreach ($this->_config as $entry)
		{
			foreach ($savedValues as $value)
			{
				if (preg_match("/" . $entry['name'] . ":/i", $value) == 1)
				{
					$buffer = explode(':', $value);
					$entry['value'] = $buffer[1];
					break;
				}
			}
			switch ($entry['typ'])
			{
				case 'i':
					// integer
					$html = '<input type="text" name = "' . $entry['name'] .
						'" value = "' . $entry['value'] . '" size = "6" />';
					break;
				case 'b':
					// boolean
					$html = '<input type="checkbox" name="' . $entry['name'] .
						'"value="' . $entry['name'] . '" ';

					if ($entry['value'] === '1')
						$html .= ' checked = "checked"';

					$html .= ' />';
					break;
				case 's':
					// string
					$html = '<select name = "' . $entry['name'] . '">';
					$values = explode(',', $entry['set']);

					foreach ($values as $option)
					{
						$html .= '<option value="' . $option . '"';
						if ($entry['value'] == $option)
							$html .= 'selected="selected"';
						$html .= '>' . $option . '</option>';
					}
					$html .= '</select>';
					break;

				default:
					break;
			}

			$data[] = array(
			 'label' => '<label for="' . $entry['name'] . '">' . $entry['text'] . '</label>',
			 'field' => $html);
		}
		$data[] = array(
		 'label' => '<label>' . _('Help') . '</label>',
		 'field' => '<div class="plugin_help_box">' . $helpx . '</div>');
		return $data;
	}

	/*
	 * Create the config array for output. 
	 * @return array assoziative with html code for template output
	 * 
	 * @param string $id			Plugin-id from database 
	 * @param string $config	Config-String with values
	 * 									Three types are possible
	 * 									scripts:: = scripts for head-area of html, copy 1:1
	 * 									head::    = e.g. scripts:: but here must set some values
	 * 													for initialize
	 * 									config::  = e.g. scripts:: but here are setting config-
	 * 													values who can set in backend
	 */

	public function getScripts($id, $config = '')
	{
		$scripts = '<!-- gallery START -->';

		$buffer = explode('|', $config);

		foreach ($buffer as $bufferx)
		{
			if (preg_match("/scripts::/i", $bufferx) == 1)
			{
				$buffery = explode('::', $bufferx);
				$scripts .= $buffery[1];
			}
			else if (preg_match("/config::/i", $bufferx) == 1)
			{
				$scripts .= $this->_script;
				$buffery = explode('::', $bufferx);
				$bufferz = explode(',', $buffery[1]);

				foreach ($bufferz as $values)
				{
					$value = explode(':', $values);
					if ($value[1] == '0' or $value[1] == 1)
					{ // Test if boolean
						foreach ($this->_config as $bool)
						{
							if ($bool['name'] == $value[0] and $bool['typ'] == 'b')
							{
								if ($value[1] == '0')
								{
									$search = '{' . $value[0] . '}';
									$scripts = str_replace($search, 'false', $scripts);
									break;
								}
								else
								{
									$search = '{' . $value[0] . '}';
									$scripts = str_replace($search, 'true', $scripts);
									break;
								}
							}
							else if ($bool['name'] == $value[0] and ( $bool['typ'] == 'i' or $bool['typ'] == 's'))
							{
								$search = '{' . $value[0] . '}';
								$scripts = str_replace($search, $value[1], $scripts);
								break;
							}
						}
						continue;
					}
					$search = '{' . $value[0] . '}';
					$scripts = str_replace($search, $value[1], $scripts);
				}
				//$buffery = '';
				//$scripts .= $buffery[1];
				//$search = '{' . $buffer[0] . '}';
				//$scripts = str_replace($search, $buffer[1], $scripts);
				//echo '>' . $search . '-->' . $buffer[1] . '<<br>';
			}
		}
		$scripts .= '<!-- gallery END -->';
		return $scripts;
	}

}

?>